package Concurrency2.Chapter02_InnerLockPrinciple.P03_ThinLock;

import org.openjdk.jol.info.ClassLayout;

import java.util.concurrent.CountDownLatch;

/**
 * 轻量级锁: 锁状态的状态变化
 */
public class ThinLock {
    //设计两个线程, 查看两个线程执行完临界区之后, 也就是都释放锁之后, 锁对象的状态
    public static void main(String[] args) {
        SomeLock someLock = new SomeLock();
        CountDownLatch subThreadcountDownLatch = new CountDownLatch(1);
        printLockObject(someLock, "轻量级锁获取之前的锁状态");

        Runnable task = () -> {
            synchronized (someLock) {
                System.out.println("ThreadID: " + Thread.currentThread().getId() + " 执行完成");
                printLockObject(someLock, "执行过程中的锁状态");
                subThreadcountDownLatch.countDown();
            }
        };

        Thread t1 = new Thread(task, "T1");
        Thread t2 = new Thread(task, "T2");
        t1.start();
        try {
            subThreadcountDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //延迟t2线程的启动
        t2.start();

        //让t1与t2都执行完成
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        printLockObject(someLock, "轻量级锁释放之后的锁状态");
    }

    private static void printLockObject(Object object, String message) {
        String lockObject = ClassLayout.parseInstance(object).toPrintable();
        System.out.println(message + ": \n" + lockObject);
    }

    static class SomeLock {
    }
}
